package com.ganbo.transation.service;

import com.ganbo.transation.entity.First;
import com.ganbo.transation.entity.Second;
import com.ganbo.transation.repository.FirstRepository;
import com.ganbo.transation.repository.SecondRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * 事务只针对 public 方法
 */
@Service
public class 事务嵌套_Service {

    @Autowired
    private FirstRepository firstRepository;
    @Autowired
    private SecondRepository secondRepository;

    @Autowired
    private OneService oneService;

    @Autowired
    事务嵌套_Service 事务嵌套_Servic;

    @Transactional
    public void 事务嵌套1() throws Exception {
        try {
            事务嵌套_Servic.saveSecond(); //注入代理对象，会回滚
            //saveSecond();  // 没有走代理,不会回滚
            //((事务嵌套_Service) AopContext.currentProxy()).saveSecond(); // 手动代理, 通过AopContext.currentProxy()获得当前代理
        } catch (Exception e) {
            e.printStackTrace();
        }
        First first = new First();
        first.setName("f-name");
        firstRepository.save(first);
    }

    @Transactional
    public void saveSecond() throws Exception {
        Second second = new Second();
        second.setName("s-name");
        secondRepository.save(second);
        int i = 1 / 0;
    }

    @Transactional
    public void 事务嵌套2() {
        try {
            oneService.saveSecond();
        } catch (Exception e) {
            e.printStackTrace();
        }

        First first = new First();
        first.setName("f-name");
        firstRepository.save(first);
    }


    public static void main(String[] args) {

        int m = 100; //红包金额
        int n = 10;  //红包个数
        int rate = 90;  //最大红包限制

        Random r = new Random();
        for (int j = 0; j < n; j++) {
            int i = r.nextInt(rate);
            rate = i;
            System.out.println(j + "个红包为:" + i);
        }
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void xiaoshiwu() {
        First one = firstRepository.getOne(1);
        System.out.println("大事务里面的值1：" + one);
        事务嵌套_Servic.xiaoshiwuTest();
        First one2 = firstRepository.getOne(1);
        System.out.println("大事务里面的值2：" + one2);
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void xiaoshiwuTest() {
        First one = firstRepository.getOne(1);
        one.setName("甘波");
        firstRepository.saveAndFlush(one);
        System.out.println("1====嵌套小事务里面修改后的值：" + one);

        First one2 = firstRepository.getOne(1);
        System.out.println("2====嵌套小事务里面修改后的值：" + one);
    }


}
